<?php

namespace app\admin\model\workorder;

use think\Model;
use traits\model\SoftDelete;

class Kbs extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'workorder_kbs';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            self::catAddKbs($row);
        });

        self::afterUpdate(function ($row) {
            $category_id     = explode(',', $row['category_id']);
            $category_id_old = isset($row['category_id_old']) ? explode(',', $row['category_id_old']) : [];
            $delete_cats     = array_diff($category_id_old, $category_id);
            self::catDelKbs(implode(',', $delete_cats), $row->id);

            // 为对应分类添加知识点关联
            self::catAddKbs($row);
        });
    }

    /**
     * 分类添加知识点关联
     */
    public static function catAddKbs($row)
    {
        $cats = Category::all($row->category_id);
        foreach ($cats as $cat) {
            $kbs_ids = $cat->kbs_ids ? explode(',', $cat->kbs_ids) : [];
            if (!in_array($row->id, $kbs_ids)) {
                $kbs_ids[]    = $row->id;
                $cat->kbs_ids = implode(',', $kbs_ids);
                $cat->save();
            }
        }
    }

    /**
     * 删除分类的关联知识点
     */
    public static function catDelKbs($category_id, $row_id)
    {
        $cats = Category::all($category_id);
        foreach ($cats as $cat) {
            $kbs_ids      = $cat->kbs_ids ? explode(',', $cat->kbs_ids) : [];
            $kbs_ids_temp = [];
            foreach ($kbs_ids as $kbs_id) {
                if ($kbs_id != $row_id) {
                    $kbs_ids_temp[] = $kbs_id;
                }
            }
            $cat->kbs_ids = implode(',', $kbs_ids_temp);
            $cat->save();
        }
    }


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list  = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
